import React, { useEffect, useRef, useState } from "react";
import { history, connect } from 'umi'
import { Tree, } from 'antd';
import TreeSetting from './components/TreeSetting'
const Categories = (props) => {
  const { list, selectedKeys, setSelectedKeys, activeTabKey, reload, dispatch, handleCallback } = props
  const [visible, setVisible] = useState({})
  const [editVisible, setEditVisible] = useState({})
  const onSelect = (keys, info) => {
    const { selected
    } = info
    if (selected) {
      setSelectedKeys(keys)
    }
  };
  const TreeList = (list) => {
    return list.map((item) => {
      const { subMaterialCategoryList, categoryName } = item;
      return {
        ...item,
        categoryName: <div onClick={(e) => {
          // e.stopPropagation()
        }} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>{categoryName}</div>
          <TreeSetting handleCallback={handleCallback} editVisible={editVisible} setEditVisible={setEditVisible} visible={visible} setVisible={setVisible} reload={reload} activeTabKey={activeTabKey} data={item}></TreeSetting>
        </div>,
        subMaterialCategoryList: subMaterialCategoryList ? TreeList(subMaterialCategoryList) : undefined,

      };
    });
  };
  const onDrop = (info) => {
    const dropKey = info.node.props.eventKey;
    const dragKey = info.dragNode.props.eventKey;
    const dropPos = info.node.props.pos.split('-');
    // 这里计算的差值 上面分析了info.dropPosition的含义   dropPosition有3种情况 
    // =0 表示拖拽到元素上
    // =1 表示拖拽到元素下面   那么放置元素的时候  应该放到这个位置+1的位置上
    // =-1 表示拖拽到元素上面   那么放置元素的时候 直接放到这个位置即可
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);


    // 递归查到元素所在树中的位置
    const loop = (data, key, callback) => {
      data.forEach((item, index, arr) => {
        if (item.id === key) {
          //在回调函数中将此元素，位置，以及元数组都返回
          return callback(item, index, arr);
        }
        if (item.subMaterialCategoryList) {
          return loop(item.subMaterialCategoryList, key, callback);
        }
      });
    };
    // 浅拷贝整个树 此处有疑问  不过不影响功能  因为怕操作data 我觉得应该深拷贝 
    const data = [...list];

    // Find dragObject 查找获取到拖拽开始的元素对象
    let dragObj;
    loop(data, dragKey, (item, index, arr) => {
      // 查找到后删除此元素  这里相当于直接操作了data 所以我认为应该深拷贝
      arr.splice(index, 1);
      dragObj = item;
    });
    if (!info.dropToGap) {
      loop(data, dropKey, item => {
        console.log(item)
        item.children = item.children || [];
        dispatch({
          type: 'liveStreaming/fakeDropMaterialCategory',
          payload: {
            id: dragKey,
            parentId: item.id ? item.id : 0,
            dropSort: 0
          },
          callback: () => {
            reload()
          }
        })
      });
    }
    // 拖拽到元素之下的缝隙中，元素有子节点，并且当前元素子节点展开。此时元素放到了子节点的第一位。（当然可以根据具体情况随意位置） 
    else if (
      (info.node.props.children || []).length > 0 && // Has children
      info.node.props.expanded && // Is expanded
      dropPosition === 1 // On the bottom gap
    ) {
      loop(data, dropKey, item => {
        item.children = item.children || [];
        console.log(item, 33333)
        // where to insert 示例添加到头部，可以是随意位置
        // item.children.unshift(dragObj);
      });
    } else {
      loop(data, dropKey, (item, index, arr) => {
        if (dropPosition === -1) {
          console.log(item, 888)
        } else {
          console.log(item, 999)
          dispatch({
            type: 'liveStreaming/fakeDropMaterialCategory',
            payload: {
              id: dragKey,
              parentId: item.parentId ? item.parentId : 0,
              dropSort: item.sortValue
            },
            callback: () => {
              reload()
            }
          })
        }

      });
    }

  }

  return <div onClick={(e) => {
    e.stopPropagation()
    setVisible(false)
    setEditVisible(false)
  }} className="Categories_box">
    <Tree
      fieldNames={{ title: 'categoryName', key: 'id', children: 'subMaterialCategoryList' }}
      onDrop={onDrop}
      autoExpandParent={true}
      blockNode
      draggable
      selectedKeys={selectedKeys}
      defaultExpandAll
      onSelect={onSelect}
      treeData={TreeList(list)}
    />
  </div>
}
export default connect(({ loading }) => ({
  loading: loading.effects['liveStreaming/fakeDropMaterialCategory'],
}))(Categories);  